//
//  StepCountDBManager.m
//  记步-Demo
//
//  Created by qinlongqing on 14/11/11.
//  Copyright (c) 2014年 qinlongqing. All rights reserved.
//

#import "StepCountDBManager.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"


#define DataBaseName         @"StepsCountInfo.sqlite"
#define TableName            @"StepsCountTable"
#define UserID               @"UserID"
#define ThisStepTime         @"ThisStepTime"


@interface StepCountDBManager ()
{
    InsertDataSuccessOrFail copyedBlock;
}

@property (nonatomic,retain) NSString *dataBasePath;
@property (nonatomic,retain) FMDatabase *myDB;
@end

@implementation StepCountDBManager

+ (StepCountDBManager *)sharedInstance{
    static StepCountDBManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
        [instance createDataBase];
    });
    return instance;
}

- (void)createDataBase{
    self.dataBasePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:DataBaseName];
    self.myDB = [FMDatabase databaseWithPath:self.dataBasePath];
    [self createTable];
}

- (void)createTable{
    if ([self.myDB open]) {
        NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' text, '%@' text)",TableName,UserID,ThisStepTime];
        BOOL res = [self.myDB executeUpdate:sqlCreateTable];
        if (!res) {
//            NSLog(@"error when creating db table");
        } else {
//            NSLog(@"success to creating db table");
        }
        [self.myDB close];
    }
}

-(void)insertStepsDataWithArray:(NSMutableArray *)stepsDataArray successOrFailBlock:(InsertDataSuccessOrFail)block{
    NSInteger insertNumber = 0;
    if ([self.myDB open]) {
        copyedBlock = Block_copy(block);
        for (int i=0; i<stepsDataArray.count; i++) {
            NSDictionary *dict = [stepsDataArray objectAtIndex:i];
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *timeString = [dateFormatter stringFromDate:[dict valueForKey:kTimeForCurrentStep]];
            
            NSString *insertSql= [NSString stringWithFormat:@"INSERT INTO '%@' ('%@', '%@') VALUES ('%@', '%@')",TableName,UserID,ThisStepTime,[dict valueForKey:kCurrentUserID],timeString];
            BOOL res = [self.myDB executeUpdate:insertSql];
            if (!res) {
//                NSLog(@"error when insert db table");
                if (copyedBlock) {
                    //.............执行一些undo操作
                    copyedBlock(NO);
                }
                return;
            }
            else{
//                NSLog(@"success to insert db table");
                insertNumber += 1;
            }
        }
        if (insertNumber == stepsDataArray.count) {
            copyedBlock(YES);
        }
        Block_release(copyedBlock);
        [self.myDB close];
    }
}

-(NSMutableArray *)selectAllStepsDataWithUserID:(NSString *)userID{
    if (userID == nil) {
        return 0;
    }
    NSMutableArray *allResultArray = [[NSMutableArray alloc]init];
    if ([self.myDB open]) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ where %@ = '%@'",TableName,UserID,userID];
        FMResultSet * rs = [self.myDB executeQuery:sql];
        while ([rs next]) {
            NSString *userID = [rs stringForColumn:UserID];
            NSString *stepTime = [rs stringForColumn:ThisStepTime];
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSDate *currentDate = [dateFormatter dateFromString:stepTime];
            
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:userID,kCurrentUserID,currentDate,kTimeForCurrentStep, nil];
            [allResultArray addObject:dict];
        }
        [self.myDB close];
    }
    return [allResultArray autorelease];
}

- (NSMutableArray *)selectStepsCountFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate WithUserID:(NSString *)userID{
    if (fromDate == nil || toDate == nil || userID == nil) {
        return 0;
    }
    NSMutableArray *allResultArray = [[NSMutableArray alloc]init];
    if ([self.myDB open]) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ where %@ = '%@'",TableName,UserID,userID];
        FMResultSet * rs = [self.myDB executeQuery:sql];
        while ([rs next]) {
            NSString *userID = [rs stringForColumn:UserID];
            NSString *stepTime = [rs stringForColumn:ThisStepTime];
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSDate *currentDate = [dateFormatter dateFromString:stepTime];
            if (([currentDate compare:fromDate] == NSOrderedDescending || [currentDate compare:fromDate] == NSOrderedSame) && ([currentDate compare:toDate] == NSOrderedAscending || [currentDate compare:toDate] == NSOrderedSame)) {
                NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:userID,kCurrentUserID,currentDate,kTimeForCurrentStep, nil];
                [allResultArray addObject:dict];
            }
        }
        [self.myDB close];
    }
    return [allResultArray autorelease];
}

- (void)dealloc{
    self.dataBasePath = nil;
    self.myDB = nil;
    
    [super dealloc];
}

@end
